package com.szrt.day20161023;

import java.util.Properties;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import org.junit.Test;

public class SendEmail {
	
	
	@Test
	public void sendemail(){
		
		//收件人电子邮箱
		String to = "987366988@qq.com";
		
		//发件人电子邮箱
		String from = "hhl324@163.com";
		
		//指定发送的主机smtp.qq.com
		//String host = "smtp.qq.com";
		String host = "smtp.163.com";
		
		//Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
	    //final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
		
		//获取系统属性
		Properties properties = System.getProperties();
		
		//设置邮件服务器
		properties.setProperty("mail.smtp.host", host);
		
		//mail.smtp.ssl.enable的值
		String xx ="mail.smtp.ssl.enable";
		
		//xx = EmailUtil.getProperty("xx"):
		properties.put(xx, "true");
		properties.put("mail.smtp.auth", "true");
		//properties.setProperty("mail.user", "myuser");
		//properties.setProperty("mail.password", "mypwd");
		
		//获取默认session对象
		Session session = Session.getDefaultInstance(properties,new Authenticator(){
			public PasswordAuthentication getPasswordAuthentication(){
				//发件人邮箱和密码  失效  优化...  qq  163  263
				//return new PasswordAuthentication("1220561123@qq.com","kphynlakfhfabaab");
				//return new PasswordAuthentication("a553838951@qq.com","gsulferzthpibfie");
				return new PasswordAuthentication("hhl324@163.com","qq123456");
			}
		});
		
		try{
			//创建默认的MimeMessage 对象
			//public class SMTPMessage extends javax.mail.internet.MimeMessage
			MimeMessage message = new MimeMessage(session);
			
			//Set From:头部头字段
			message.setFrom(new InternetAddress(from));
			
			//Set To:头部头字段
			message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
			
			//Set Subject:头部头字段
			message.setSubject("eat g001");
			
			//设置消息体
			message.setText("可以吃饭啦 go go...");
			
			
			//发送消息
			Transport.send(message);
			System.out.println("Send message successfully....");
		}catch(MessagingException mex){
			mex.printStackTrace();
		}
	}

}
